package com.example.myapplication.shortvideo.utils;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import androidx.annotation.NonNull;
import android.view.MotionEvent;
import android.view.View;

/**
 * @author: rongfeng
 * @date: 2020/6/17
 * @description
 */
public class DoubleClick implements View.OnClickListener {


    public interface DoubleClickListener {
        void click();
        void doubleClick();
    }

    private View view;
    private long lastClickTime;
    private DoubleClickListener mDoubleClickListener;
    private int time;

    public DoubleClick(View view, int time, DoubleClickListener clickListener) {
        this.view = view;
        this.view.setOnClickListener(this);
        this.mDoubleClickListener = clickListener;
        this.time = time;
    }

    public static DoubleClick setDoubleClickListener(View view, int time, DoubleClickListener clickListener) {
        return new DoubleClick(view, time, clickListener);
    }


//    @Override
//    public boolean onTouch(View v, MotionEvent event) {
//        if (event.getAction() == MotionEvent.ACTION_DOWN) {
//            long currentTimeMillis = System.currentTimeMillis();
//            handler.removeMessages(1);
//            if (currentTimeMillis - lastClickTime < time) {
//                lastClickTime = 0;
//                mDoubleClickListener.doubleClick();
//            } else {
//                lastClickTime = System.currentTimeMillis();
//                handler.sendEmptyMessageDelayed(1, time);
//            }
//        }
//        return false;//让点击事件继续传播，方便再给View添加其他事件监听
//    }



    @Override
    public void onClick(View view) {
        long currentTimeMillis = System.currentTimeMillis();
        handler.removeMessages(1);
        if (currentTimeMillis - lastClickTime < time) {
            lastClickTime = 0;
            mDoubleClickListener.doubleClick();
        } else {
            lastClickTime = System.currentTimeMillis();
            handler.sendEmptyMessageDelayed(1, time);
        }
    }


    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (view != null) {
                    lastClickTime = 0;
                    mDoubleClickListener.click();
                }
            }
        }
    };


    public void release() {
        handler.removeMessages(1);
        handler = null;
    }

}
